package com.software.levelupserver.config;

import com.software.levelupserver.auth.AppAccessDenyHandler;
import com.software.levelupserver.auth.AppAuthenticationFailHandler;
import com.software.levelupserver.auth.AppAuthenticationSuccessHandler;
import com.software.levelupserver.filter.JwtCheckFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private AppAuthenticationSuccessHandler appAuthenticationSuccessHandler;
    @Resource
    private AppAuthenticationFailHandler appAuthenticationFailHandler;
    @Resource
    private AppAccessDenyHandler appAccessDenyHandler;
    @Resource
    private JwtCheckFilter jwtCheckFilter;
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .addFilterBefore(jwtCheckFilter, UsernamePasswordAuthenticationFilter.class)
                .csrf().disable()
                .formLogin()
                .usernameParameter("email")
                .successHandler(appAuthenticationSuccessHandler)
                .failureHandler(appAuthenticationFailHandler)
                .and()
                .exceptionHandling()
                .accessDeniedHandler(appAccessDenyHandler)
                .and()
                .sessionManagement((sessionManagementConfigurer)->
                        sessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        ;
    }
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean()
            throws Exception {
        return super.authenticationManagerBean();
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
